import * as React from "react";
import { inject, observer } from "mobx-react";
import { Modal, message } from 'antd';
import { History, Location } from 'history';
import { AuthObjectStore, AppStore } from '../../../../store';
import PublicTable from '../../../common/PublicTable';
import EditModal from '../../../common/editModal/EditModal';
import HeaderButton from '../../../common/header-button/HeaderButton';
import { upsertAsync, batchDeleteAsync } from '../../../../basicData/api';
import { dateFormat } from '../../../../util/util';

interface IProps {
  authObjectStore: AuthObjectStore;
  appStore: AppStore;
  history: History;
  location: Location;
  children?: AudioContextLatencyCategory;
}


interface State {
  visible: boolean;
  authObject: {
    objectCode: string,
    objectName: string,
    isTailNode: number,
    parentObjectId?: number,
    isActive: boolean
  };
}

//初始化state
const initialState: State = {
  visible: false,
  authObject: {
    objectCode: '',
    objectName: '',
    isTailNode: 0,
    isActive: true
  },
};

type IState = Readonly<typeof initialState>;

@inject("authObjectStore")
@inject("appStore")
@observer
class AuthObject extends React.Component<IProps, IState> {
  readonly state: IState = initialState

  componentDidMount() {
    this.props.authObjectStore.getAuthObjectTree()
  }

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  }

  handleCreate = (values: { objectCode: string, objectName: string }) => {
    let param = this.state.authObject
    param.objectCode = values.objectCode;
    param.objectName = values.objectName;
    upsertAsync('AuthObject', param).then((res: any) => {
      if (res.success) {
        this.setState({
          visible: false,
        })
        this.props.authObjectStore.getAuthObjectTree()
      } else {
        message.error(res.error.message)
      }
    })
  }

  add = (record: any) => {
    this.setState({
      visible: true,
      authObject: {
        objectCode: '',
        objectName: '',
        isTailNode: 0,
        parentObjectId: record.id,
        isActive: true
      }
    });
  }

  delete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除权限：【 ${record.objectName} 】？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        batchDeleteAsync('AuthObject', [record.id]).then((res: any) => {
          if (res.success) {
            this.props.authObjectStore.getAuthObjectTree()
          } else {
            message.error(res.error.message)
          }
        })
      },
    })
  }

  render() {
    const { selectedRows } = this.props.appStore
    const columns = [
      {
        title: '权限编码',
        dataIndex: 'objectCode',
        key: 'objectCode',
      }, {
        title: '权限名称',
        dataIndex: 'objectName',
        key: 'objectName',
      }, {
        title: '创建日期',
        dataIndex: 'creationTime',
        key: 'creationTime',
        render: (text: string, record: any) => {
          return dateFormat(text)
        }
      }, {
        title: '操作', key: 'operation', render: (text: string, record: any) => {
          return (
            <div>
              <a onClick={() => this.add(record)}> 追加</a>
              {/* <a onClick={() => this.delete(record)}> 删除</a> */}
            </div>
          )
        }
      }
    ];

    const addValue = [
      {
        type: 'input',
        name: '权限编码',
        key: 'objectCode',
        rule: { required: true, message: '请输入编码' }
      },
      {
        type: 'input',
        name: '权限名称',
        key: 'objectName',
        rule: { required: true, message: '请输入名称' }
      },
    ]

    const buttonConfig = {
      content: {
        isDelete: true,
        isPlus: true,
        isBind: false,
        plusTxt: '增加根权限'
      },
      columns,
      plus: () => {
        this.setState({
          visible: true,
          authObject: {
            objectCode: '',
            objectName: '',
            isTailNode: 0,
            isActive: true
          }
        });
      },
      batchDelete: () => {
        let ids: string[] = [];
        let names: string[] = [];
        let _this = this;
        selectedRows.map((selectedRowKey) => {
          ids.push(selectedRowKey.id)
          names.push(selectedRowKey.objectName)
        })
        Modal.confirm({
          title: '确认删除',
          content: `确认删除权限：【 ${names.join('，')} 】？`,
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            batchDeleteAsync('AuthObject', ids)
              .then((res: any) => {
                if (res.success) {
                  _this.props.authObjectStore.getAuthObjectTree()
                } else {
                  message.error(res.error.message)
                }
              })
          },
        })
      },
    }

    return (
      <div>
        <HeaderButton
          {...buttonConfig}
        />
        <PublicTable
          columns={columns}
          dataSource={{
            totalCount: this.props.authObjectStore.authObjectTreeCount,
            items: this.props.authObjectStore.authObjectTree.slice().sort()
          }}
          style={{ marginTop: '10px' }}
        />
        <EditModal
          title={'新增权限'}
          isNew={true}
          values={{}}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          editconfig={addValue}
        />
      </div>)
  }
}

export default AuthObject
